package com.sample.web

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.groovyflow.spring.locator.BeanLocator;
import org.groovyflow.spring.locator.BeanLocatorImpl;
import org.springframework.showcase.coverc.domain.Recipe;
import org.springframework.showcase.coverc.service.RecipeManager;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.ServletRequestUtils;


class EditRecipeNewController {

    private BeanLocator beanLocator = new BeanLocatorImpl();

    private RecipeManager getRecipeManager(){
    	return (RecipeManager) beanLocator.getBean("recipeManager");
    }
    
    def get(request, response){
    	println ("hit EditRecipeNewController.get()")
    	setup(request, response)
    }
    
    def setup(request, response) {

        long id = ServletRequestUtils.getRequiredLongParameter(request, "id");
        Recipe recipe = this.getRecipeManager().findById(new Long(id));
        request.setAttribute("id", recipe.getId());
        request.setAttribute("name", recipe.getName());
        return  new ModelAndView("newEditRecipe");
    }   
    
    def save(req, res){
    	def name = req.getParameter("name")
    	def id = req.getParameter("id")
    	
    	Recipe recipe = this.getRecipeManager().findById(Long.parseLong(id));
    	recipe.name = name
    	this.getRecipeManager().save(recipe);
    	
		req.setAttribute("topString", "##From EditRecipeNewController: It's still Groovy##");
    	
    	//This also works
    	//return new ModelAndView("redirect:fun_tryit.do")
  
    	return new ModelAndView("switchboard").addObject(this.getRecipeManager().findAll());
    } 
    	

}